#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

void put(struct sockaddr_in addr,char* cmd)
{
	char* filename;
	int fd,filefd;
	int ret,filesize,n;
	char buf[BUFSIZ];//8KB
	char* sendinfo;

	/*买电话*/
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}

	/*打电话*/ 
	ret = connect(fd, (struct sockaddr*)&addr, sizeof(addr));	
	if (ret == -1) 
	{
		perror("connect");
		exit(1);
	}
	
	/*发送命令*/
	ret = send(fd,cmd,strlen(cmd), 0);
	if (ret == -1) 
	{
		perror("send");
		exit(1);
	}
	usleep(500000);//等待服务器接收完命令

	/*查询文件是否存在*/
	strtok(cmd," ");
	filename = strtok(NULL," ");
	filename[strlen(filename)-1] = '\0';//把末尾的'\n'去掉
	filefd = open(filename,O_RDONLY);
	if(filefd < 0)
	{
		perror("open");
		printf("文件不存在，请上传其他文件。\n");
		sendinfo = "NO";
		write(fd,sendinfo,strlen(sendinfo));
		return;
	}
	printf("文件存在，开始上传……\n");
	sendinfo = "YES";
	write(fd,sendinfo,strlen(sendinfo));	
	
	/*发送文件*/
	//计算文件大小
	filesize = lseek(filefd,0,SEEK_END);//把位置指针移到文件末尾，并读取此时的字节数即文件大小
	lseek(filefd,0,SEEK_SET);//把位置指针重置到文件开头
	printf("filesize:%d\n",filesize);
	
	//复制
	n = filesize/BUFSIZ;
	while(n--)
	{
		if(read(filefd,buf,BUFSIZ) == BUFSIZ)
		{
			write(fd,buf,BUFSIZ);
			bzero(buf, BUFSIZ);
			filesize = filesize -BUFSIZ;
			usleep(100000);//延时，避免粘包
		}
		else
			printf("客户端上传文件时出错！\n");
	}

	if(filesize > 0)
	{
		read(filefd,buf,filesize);
		write(fd,buf,filesize);
	}

	/*关闭文件*/
	close(filefd);
	printf("客户端上传文件已完成。\n");

	/*挂电话*/
	close(fd);
}



